package zhou.chs.p4_7;

import android.app.PendingIntent;
import android.content.Intent;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    private NfcAdapter mNfcAdapter;
    private PendingIntent pend;
    private Tag tag;
    private TextView cardID;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        cardID=(TextView)findViewById(R.id.idtv1);
        mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
        cardID.setText("等待读卡...");
        //监听NFC标签，发现后发送一个Intent给当前Activity，调用onNewIntent方法
        pend = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
    }
    //启动监听
    protected void onResume() {
        super.onResume();
        mNfcAdapter.enableForegroundDispatch(this, pend, null, null);
    }
    //取消监听
    protected void onPause() {
        super.onPause();
        if (mNfcAdapter != null) {
            mNfcAdapter.disableForegroundDispatch(this);
        }
    }
    //监听响应，
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        tag=intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);//获取到Tag标签对象
        if(tag!=null){
            byte[] rfid = new byte[4];
            String strid = "";
            rfid=tag.getId();
            for(int i=0;i<4;i++) strid+=String.format("%02X",rfid[i]); //转换成16进制
            cardID.setText("ID: " + strid);  //显示卡片的ID
        }else{
            return;
        }
    }
}
